package com.zjj.shiro.authentication;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.Test;

public class LoginLogoutTest {

	/**
	 * user配置
	 * 
	 */
	@Test
	public void testHellWorld() {
		 //1、获取SecurityManager工厂，此处使用Ini配置文件初始化SecurityManager
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");

        //2、得到SecurityManager实例 并绑定给SecurityUtils
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);

        //3、得到Subject及创建用户名/密码身份验证Token（即用户身份/凭证）
        UsernamePasswordToken token = new UsernamePasswordToken("zjj", "123");
        Subject subject = SecurityUtils.getSubject();
        try {
            //4、登录，即身份验证
            subject.login(token);
        } catch (AuthenticationException e) {
            //5、身份验证失败
        	System.out.println("用户名或密码错误！");
        }
        System.out.println("登录状态：" + subject.isAuthenticated());
        //6、退出
        subject.logout();
	}
	
	@Test
	public void testRealm() {
		Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-realm.ini");
		
		SecurityManager securityManager = factory.getInstance();
		SecurityUtils.setSecurityManager(securityManager);
		
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken("zjj", "123");
		try {
			subject.login(token);
		} catch (Exception e) {
			System.out.println("====" + e.getMessage());
		}
		System.out.println("登录状态：" + subject.isAuthenticated());
		subject.logout();
	}
	
	@Test
	public void testMultiRealm() {
		Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-multi.ini");
		
		SecurityManager securityManager = factory.getInstance();
		SecurityUtils.setSecurityManager(securityManager);
		
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken("fx","123");
		
		try {
			subject.login(token);
		} catch (Exception e) {
			System.out.println("====" + e.getMessage());
		}
		System.out.println("登录状态：" + subject.isAuthenticated());
		subject.logout();
	}
	
	
	
}
